package com.itheima.controller;

import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.ArticleService;
import com.itheima.utils.UserHolder;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 新增/发布文章
     * @param article
     * @return
     */
    @PostMapping
    public Result add(@RequestBody @Validated(Article.Add.class) Article article) {
        articleService.add(article);
        return Result.success();
    }

    /**
     * 条件分页列表查询（当前用户的）
     * @param pageNum 页号
     * @param pageSize 页大小
     * @param categoryId 分类id（非必须）
     * @param state 文章状态（非必须）
     * @return
     */
    @GetMapping
    public Result<PageBean<Article>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state) {
        PageBean<Article> pageBean = articleService.list(pageNum, pageSize, categoryId, state);
        return Result.success(pageBean);
    }

    /**
     * 更新文章
     * @param article
     * @return
     */
    @PutMapping
    public Result update(@RequestBody @Validated(Article.Update.class) Article article) {
        Map<String, Object> map = UserHolder.get();
        Integer userId = (Integer) map.get("id");
        Article oldArticle = articleService.findById(article.getId());
        if(!oldArticle.getCreateUser().equals(userId)) {
            return Result.error("你只能修改自己的帖子");
        }
        articleService.update(article);
        return Result.success();
    }

    /**
     * 获取一个文章的详情
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public Result<Article> detail(@RequestParam Integer id) {
        Article article = articleService.findById(id);
        return Result.success(article);
    }

    @DeleteMapping
    public Result delete(@RequestParam Integer id) {
        articleService.deleteById(id);
        return Result.success();
    }

}
